package BLC

import (
	"flag"
	"fmt"
	"log"
	"os"
)

type CLI struct {
	BC *BlockChain
}

func printUseage()  {

	fmt.Println("Usage:")
	fmt.Println("\tcreate block chain with genesis -data -- 交易数据...")
	fmt.Println("\taddblock-data DATA -- 交易数据..")
	fmt.Println("\tprintchain -- 输入区块信息.")
}

// 判断参数是否合法
func isValidArgs()  {
	if len(os.Args) < 2 {
		printUseage()
		os.Exit(1)

	}
}

// 命令行添加区块
func (cli *CLI) addBlock(data string)  {
	cli.BC.AddBlockToBlockchain(data)
}

func (cli *CLI) printchain()  {
	cli.BC.Printchain()
}

func (cli *CLI) createGenesisBlockchain(data string)  {

	fmt.Println(data)
}

func (cli *CLI) Run()  {
	isValidArgs()

	addBlockCmd := flag.NewFlagSet("addblock",flag.ExitOnError)
	printChainCmd := flag.NewFlagSet("printchain",flag.ExitOnError)
	createBlockchainCmd := flag.NewFlagSet("createblockchain",flag.ExitOnError)

	flagAddBlockData := addBlockCmd.String("data","默认数据","创建新区快数据")
	flagCreateBlockchainWithData := createBlockchainCmd.String("data","创世区块创建","创世区快数据")

	switch os.Args[1] {
	case "addblock":
		err := addBlockCmd.Parse(os.Args[2:])
		if err != nil {
			log.Panic(err)
		}
	case "printchain":
		err := printChainCmd.Parse(os.Args[2:])
		if err != nil {
			log.Panic(err)
		}
	case "createblockchain":
		err := createBlockchainCmd.Parse(os.Args[2:])
		if err != nil {
			log.Panic(err)
		}
	default:
		printUseage()
		os.Exit(1)
	}

	if addBlockCmd.Parsed(){
		if *flagAddBlockData == ""{
			printUseage()
			os.Exit(1)
		}

		cli.addBlock(*flagAddBlockData)
	}

	if printChainCmd.Parsed(){
		cli.printchain()
	}

	if createBlockchainCmd.Parsed(){
		if *flagCreateBlockchainWithData == "" {
			fmt.Println("交易数据不能为空....")
			printUseage()
			os.Exit(1)
		}

		cli.createGenesisBlockchain(*flagCreateBlockchainWithData)
	}



}
